
#include <sys/time.h>
#include <time.h>
#include "hj212message.h"

HJ212Msg* HJ212_create_message(const char* qn, const unsigned char st, const unsigned short cn, const char* pwd, const char* mn, char flag, const char* payload, int length)
{
    HJ212Msg* ret = malloc(sizeof(HJ212Msg) + length+1);

    if( ret  )
    {
        ret->qn = (char*)malloc(strlen(qn) + 1);
        ret->st = st;
        ret->cn = cn;
        ret->flag = flag;
        if ( pwd )
            ret->pwd = (char*)malloc(strlen(pwd) + 1);
        else
            ret->pwd = NULL;
        ret->mn = (char*)malloc(strlen(mn) + 1);
        if (ret->mn && ret->qn )
        {
            strcpy(ret->mn, mn);
            strcpy(ret->qn, qn);
            if ( pwd )
                strcpy(ret->pwd, pwd);
            if( payload )
            {
                strncpy((char*)(ret + 1), payload, length);
                ((char*)(ret + 1))[length] = '\0';
            }
        }
        else
        {
            free(ret->mn);
            free(ret->qn);
            free(ret->pwd);
            free(ret);
            ret = NULL;
        }
    }

    return ret;
}

#define HJ212_QN_LENGTH           17
char* Hj212_qn_new(void)
{
     char* qn = NULL;
    struct timeval time_ms = { 0 };
    struct tm *tm_t = NULL;

    gettimeofday(&time_ms, NULL);
    time_t seconds = time_ms.tv_sec;
    tm_t = localtime(&seconds);
    if ( tm_t) 
    {
        qn = malloc(HJ212_QN_LENGTH + 1);
        if ( qn )
        {
            snprintf(qn, HJ212_QN_LENGTH, "%04d%02d%02d%02d%02d%02d%03ld",
             tm_t->tm_year + 1900, tm_t->tm_mon + 1, tm_t->tm_mday,
             tm_t->tm_hour, tm_t->tm_min, tm_t->tm_sec, (time_ms.tv_usec / 1000));
            qn[HJ212_QN_LENGTH] = '\0';
        }
    }

    return qn;
    
   
}

void HJ212_destroy_message(HJ212Msg* msg)
{
    if ( msg )
    {
        free(msg->qn);
        free(msg->pwd);
        free(msg->mn);
        free(msg);
    }
}

int Hj212_size(HJ212Msg* msg)
{
    int size = sizeof(HJ212Msg);

    if ( size )
    {
        size += strlen(msg->qn);
        size += strlen(msg->pwd);
        size += strlen(msg->mn);
        size += strlen(msg->payload);
    }

    return size;
}